package com.xiaoxiang.mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxiang.common.api.CreateOrderParam;
import com.xiaoxiang.common.api.CreateOrderResult;
import com.xiaoxiang.common.result.HttpResult;
import com.xiaoxiang.mall.api.PayService;
import com.xiaoxiang.mall.entity.OrderInfo;
import com.xiaoxiang.mall.service.OrderInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * (OrderInfo)表控制层
 *
 * @author haha
 * @since 2022-05-05 14:18:58
 */
@RestController
@RequestMapping("orderInfo")
public class OrderInfoController {
    /**
     * 服务对象
     */
    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private PayService payService;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param orderInfo 查询实体
     * @return 所有数据
     */
    @GetMapping("list")
    public HttpResult selectAll(Page<OrderInfo> page, OrderInfo orderInfo) {
        page.addOrder(OrderItem.desc("create_time"));
        return HttpResult.success(this.orderInfoService.page(page, new QueryWrapper<>(orderInfo)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping
    public HttpResult selectOne(@RequestParam Long id) {
        return HttpResult.success(this.orderInfoService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param orderInfo 实体对象
     * @return 新增结果
     */
    @PostMapping
    public HttpResult insert(@RequestBody OrderInfo orderInfo) {
        orderInfo.setCreateTime(new Date());
        orderInfo.setState("待支付");
        CreateOrderParam createOrderParam = CreateOrderParam.builder()
                .payeeUserId(orderInfo.getUserId())
                .draweeUserId(-1L)
                .subject("商品购买")
                .amount(orderInfo.getTotalAmount())
                .build();
        CreateOrderResult result = payService.createOrder(createOrderParam).getData();
        orderInfo.setPayOrderId(result.getOrderId());
        this.orderInfoService.save(orderInfo);
        return HttpResult.success(result);
    }

    /**
     * 修改数据
     *
     * @param orderInfo 实体对象
     * @return 修改结果
     */
    @PutMapping
    public HttpResult update(@RequestBody OrderInfo orderInfo) {
        return HttpResult.success(this.orderInfoService.updateById(orderInfo));
    }

    /**
     * 删除数据
     *
     * @return 删除结果
     */
    @DeleteMapping
    public HttpResult delete(@RequestParam("id") Long id) {
        return HttpResult.success(this.orderInfoService.removeById(id));
    }
}
